/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * email:nur01@qq.com
 * @flow
 */

import React, {Component} from 'react';
import {
    DeviceEventEmitter,
    Image,
    ListView,
    Moment,
    RefreshControl,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from 'react-native';
import StyleUtils from "../../../res/styles/StyleUtils";
import Navigation from "../../../custom/Navigation";
import ViewUtils from "../../../utils/ViewUtils";
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view'
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import I18n from '../../../res/language/i18n'
import RegisterIBMTowPage from "./RegisterIBMTowPage";
import CommonUtils from "../../../common/CommonUtils";
import DateTimePicker from 'react-native-modal-datetime-picker';

import moment from 'moment';
import ModalListUtils from "../../../utils/ModalListUtils";
import IparInput from "../../../custom/IparInput";


export default class RegisterIBMOnePage extends Component {


    constructor(props) {
        super(props);

        this.sexData = new ListView.DataSource({
            rowHasChanged: (r1, r2) => r1 !== r2,
        }).cloneWithRows([I18n.t('default.female'), I18n.t('default.male'), I18n.t('default.secrecy'),]);
        this.iparNetwork = new IparNetwork();

        this.firstName = '';
        this.middleName = '';
        this.familyName = '';
        this.userEmail = '';

        this.state = {
            isDateTimePickerVisible: false,

            //userInfo
            userBirthday: I18n.t('default.enterBirthday'),
            isChecked: false,
            loading: false,
            modalVisible: false,
            sexText: I18n.t('default.gender'),
            sex: -1,
            userAgeFull: false,
        }
    }


    /**
     * DateTimePicker
     * */
    _showDateTimePicker = () => this.setState({
        isDateTimePickerVisible: true,
    });
    _hideDateTimePicker = () => this.setState({isDateTimePickerVisible: false});
    _handleDatePicked = (date) => {
        let dateFormat = moment(date).format("YYYY-MM-DD");

        this.setState({
            userBirthday: dateFormat,
            isDateTimePickerVisible: false,
            userAgeFull: !new CommonUtils().ageOf18(moment(date).format("YYYY/MM")),
        });
    };


    /**
     * 点击 MEX
     */
    submit(type) {
        if (!this.firstName.trim()) {
            DeviceEventEmitter.emit('toast', I18n.t('default.firstName'));
            return;
        }
        if (!this.familyName.trim()) {
            DeviceEventEmitter.emit('toast', I18n.t('default.familyName'));
            return;
        }
        // if (!this.userEmail.trim()) {
        //     DeviceEventEmitter.emit('toast', I18n.t('default.interEmail'));
        //     return;
        // }

        if (this.userEmail.trim() && !CommonUtils.checkEmail(this.userEmail)) {
            DeviceEventEmitter.emit('toast', I18n.t('toast.emailFormatError'));
            return;
        }

        if (this.state.userBirthday === I18n.t('default.enterBirthday')) {
            DeviceEventEmitter.emit('toast', I18n.t('default.enterBirthday'));
            return;
        }
        if (this.state.userAgeFull) {
            DeviceEventEmitter.emit('toast', I18n.t('toast.registrantOver'));
            return;
        }
        if (this.state.sexText === I18n.t('default.gender')) {
            DeviceEventEmitter.emit('toast', I18n.t('default.gender'));
            return;
        }

        CommonUtils.showLoading();

        if (this.userEmail.trim()) {
            this.iparNetwork.getRequest(SERVER_TYPE.admin + 'checkUserKey?', 'keywords=' + this.userEmail)
                .then((result) => {
                    if (result.code === 200) {
                        if (this.props.userId === result.data.main_user_id) {
                            this.saveUserInfo(type);
                        } else {
                            CommonUtils.dismissLoading();
                            DeviceEventEmitter.emit('toast', I18n.t('toast.emailAddrssTaken'))
                        }
                    } else {
                        this.saveUserInfo(type);
                    }
                })
                .catch((error) => {
                    CommonUtils.dismissLoading();

                    console.log('RegisterIBMOnePage--submit-error: ', error);
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
                })
        } else {
            this.saveUserInfo(type);
        }
    }


    /**
     *
     * @param type
     */
    saveUserInfo(type) {
        let formData = new FormData();
        formData.append('user_id', this.props.userId);
        formData.append('first_name', this.firstName);
        formData.append('middle_name', this.middleName);
        formData.append('last_name', this.familyName);
        formData.append('birth_day', this.state.userBirthday);
        formData.append('sex', this.state.sex);
        formData.append('email', this.userEmail);

        this.iparNetwork.getPostFrom(SERVER_TYPE.admin + 'updateUserInfo', formData)
            .then((result) => {
                CommonUtils.dismissLoading();
                if (result.code === 200) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                    if (type === 1) {
                        new CommonUtils().popToRoute(this, 'LoginPage')
                    } else {
                        this.startNex();
                    }
                } else {
                    console.log('RegisterIBMOnePage--saveUserInfo-fail: ', result);
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();
                console.log('RegisterIBMOnePage--saveUserInfo-error: ', error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            })

    }


    /**
     * 条第二个注册页面
     */
    startNex() {
        this.props.navigator.push({
            component: RegisterIBMTowPage,
            name: 'RegisterIBMTowPage',
            params: {
                userId: this.props.userId,
            }
        })

    }


    /**
     * 更新state
     * @param dic
     */
    updateState(dic) {
        this.setState(dic)
    }

    /**
     * init
     * */
    render() {
        return (
            <View style={StyleUtils.flex}>
                <Navigation
                    titleImage={require('../../../res/images/ic_ipar_logo.png')}
                    onClickLeftBtn={() => {
                        new CommonUtils().popToRoute(this, 'LoginPage')
                    }}/>

                <KeyboardAwareScrollView

                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.loading}
                            onRefresh={() => {
                            }}
                        />
                    }
                >
                    <View style={{padding: 16}}>

                        {/*title*/}
                        {ViewUtils.getTitleView(I18n.t('default.register'), I18n.t('default.personalInformation'))}

                        {/*inputs*/}
                        <IparInput
                            onChangeText={(text) => this.firstName = text}
                            placeholder={I18n.t('default.firstName')}/>

                        {this.props.country !== 'CN' ?
                            <IparInput
                                onChangeText={(text) => this.middleName = text}
                                placeholder={I18n.t('default.middleName')}/> : null}

                        <IparInput
                            onChangeText={(text) => this.familyName = text}
                            placeholder={I18n.t('default.familyName')}/>


                        <IparInput
                            onChangeText={(text) => this.userEmail = text}
                            placeholder={I18n.t('default.interEmail')}/>

                        {ViewUtils.getButtunMenu(this.state.userBirthday, () => this._showDateTimePicker(), StyleUtils.marginTop)}

                        {ViewUtils.getButtunMenu(this.state.sexText, () => {
                            this.setState({
                                modalVisible: true
                            })
                        }, StyleUtils.marginTop)}


                        <ModalListUtils
                            onPress={(index, text) => {
                                this.setState({
                                    sexText: text,
                                    sex: index,
                                    modalVisible: false,
                                })
                            }}
                            visible={this.state.modalVisible}
                            dataSource={this.sexData}
                            title={I18n.t('default.selectSex')}
                            close={() => {
                                this.setState({
                                    modalVisible: false
                                })
                            }}
                        />
                        <DateTimePicker
                            isVisible={this.state.isDateTimePickerVisible}
                            titleIOS={I18n.t('default.enterBirthday')}
                            onConfirm={this._handleDatePicked}
                            onCancel={this._hideDateTimePicker}
                        />


                        {/*/!*CheckBox*!/*/}
                        {/*<CheckBox*/}
                        {/*checkBoxColor={'#333333'}*/}
                        {/*style={StyleUtils.marginTop}*/}
                        {/*onClick={() => {*/}
                        {/*this.setState({*/}
                        {/*isChecked: !this.state.isChecked,*/}
                        {/*})*/}
                        {/*}}*/}
                        {/*isChecked={this.state.isChecked}*/}
                        {/*rightText={I18n.t('default.registerIsOver')}*/}
                        {/*/>*/}

                        {ViewUtils.getButton(I18n.t('default.next'), () => this.submit(0), StyleUtils.marginTop)}
                        {ViewUtils.getButton(I18n.t('default.zanCun'), () => this.submit(1), [StyleUtils.marginTop, styles.zanBtn], {color: 'black'})}
                    </View>
                </KeyboardAwareScrollView>

            </View>
        );
    }
}

const styles = StyleSheet.create({
    zanBtn: {
        backgroundColor: 'white',
        borderWidth: 1,
        borderColor: 'black',
    }
});


